/**
 * comment controllers
 */
var Comment = require('../models/comment.js');

var MESSAGES = {
    DATAMISS : '缺少必要数据！',
    NOTLOGIN : '未登录，请登录后再操作！',
    SUCCESS  : '操作成功！',
    FAIL     : '操作失败！请稍后再试~'
};

exports.getComments = function(req, res){

    if(!req.body.postId){

        res.json({code: 0, msg: MESSAGES.DATAMISS});

    } else{
        Comment.findByPostId(req.body.postId, req.session.sid, function (e, comments){

            if(e){

                res.json({code: 0, msg: e});

            } else {

                res.json({code: 1, obj: comments});

            }
        });
    }
};

exports.addComment =  function(req, res){

    if(!req.session.sid){

        res.json({code: 0, msg: MESSAGES.NOTLOGIN});

    } else {

        Comment.addComment(req.body, req.session.sid, function(e, c){

            if(e){
                res.json({code: 0, msg: e});
            } else {
                res.json({code: 1, comment: c});
            }
        });
    }
};

exports.deleteComment = function (req, res) {
    if(req.body.id) {
        Comment.deleteCommentById(req.body.id, function (e, numberAffected) {
            if (e || numberAffected != 1) {
                res.json({code: 0, msg: MESSAGES.FAIL});
            } else {
                res.json({code: 1, msg: MESSAGES.SUCCESS});
            }
        });
    } else {
        res.json({code: 0, msg: MESSAGES.DATAMISS});
    }
};

exports.deleteCommentsByUserName = function(name, callback){
    Comment.deleteCommentsByUserName(name, callback);
};